package com.xiaojiang.interceptors;

import com.xiaojiang.pojo.Result;
import com.xiaojiang.utils.JwtUtil;
import com.xiaojiang.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 功能：拦截器 
 * 作者：小江
 * 日期：2024年08月02日
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //preHandle请求到达接口之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //解析token
        try {
            //从redis中获取相同的token
            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
            String redisToken = stringStringValueOperations.get(token);
            if (redisToken==null){
                 //token已经失效
                throw new RuntimeException();
            }

            Map<String,Object> claims = JwtUtil.parseToken(token);
            //把业务数据存到ThreadLocal里面
            ThreadLocalUtil.set(claims);

            //放行
            return true;
        } catch (Exception e) {
            //http状态响应码为401
            response.setStatus(401);
            return false;
        }
    }

    //afterCompletion请求接口结束后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完清空ThreadLocal中的数据，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
